﻿/*
 * 教程：https://www.youtube.com/watch?v=4HpC--2iowE
 */

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController characterController;
    public float speed = 12f;
    public float turnSmoothTime = 0.1f;
    public float turnSmoothVelocity;

    public float gravity = -20f; //重力的加速度。

    private Vector3 veclocity;

    public Transform groundCheck;
    public float groundDistance = 0.4f;//检测触碰到地图的圆的半径。
    public LayerMask groundMask;
    public bool isGrounded;

    public float jumpHeight = 3f;
    private bool jump2 = false;

    // Start is called before the first frame update
    private void Start()
    {
    }

    // Update is called once per frame
    private void Update()
    {
        // 是否与地面碰撞。表示在 groundCheck 上创建一个不可见的球面，并检测是否与指定的图层（地面）发生碰撞。
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && veclocity.y < 0)
        {
            // 如果在地面上，则重置下落速度。
            veclocity.y = -5f;

            // 二段跳。
            jump2 = false;
        }

        //float horizontal = Input.GetAxis("Horizontal");
        //float vertical = Input.GetAxis("Vertical");

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        // 进行标准化，取到向量固定的距离，否则会出现直走慢，斜走快的 BUG。
        var direction = new Vector3(x, 0, z).normalized;

        if (direction.magnitude > 0.1f)
        {
            //// 目标位置 = 角色当前的位置 X 向量
            //Vector3 move = transform.right * direction.x + transform.forward * direction.z;

            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + Camera.main.transform.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            characterController.Move(moveDir.normalized * speed * Time.deltaTime);
        }

        // 跳跃。
        if (Input.GetButtonDown("Jump") && (isGrounded || jump2 == false))
        {
            // 跳跃 = (高度 X -2 X 重力加速度)平方根。
            veclocity.y += Mathf.Sqrt(jumpHeight * -2 * gravity);

            // 二段跳。
            if (!isGrounded)
            {
                jump2 = true;
            }
        }

        // 根据自由落体原理。
        veclocity.y += gravity * Time.deltaTime;

        characterController.Move(veclocity * Time.deltaTime);
    }
}